package br.ufrj.dcc.ad.stats;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import br.ufrj.dcc.ad.ScatterPlotChart;
import br.ufrj.dcc.ad.event.Event;
import br.ufrj.dcc.ad.event.PackageReceivedByRouterEvent;
import br.ufrj.dcc.ad.model.BackgroundPackage;
import br.ufrj.dcc.ad.model.Package;

public class DiscardsStats extends Statistics {
	
	private List<Map<Double, Double>> listMap;

	public DiscardsStats(String title, String xLabel, String yLabel, Integer... sessionIds) {
		super(title, xLabel, yLabel);
		this.listMap = new ArrayList<Map<Double, Double>>();
		for (@SuppressWarnings("unused") Integer id : sessionIds) {
			this.listMap.add(new TreeMap<Double, Double>());
		}
	}

	@Override
	protected void doStatistic(Event event) {
		if (!(event instanceof PackageReceivedByRouterEvent)) return;
		final PackageReceivedByRouterEvent routerEvent = (PackageReceivedByRouterEvent) event;
		final Package pack = routerEvent.getPackage();
		if (pack instanceof BackgroundPackage) return;
		if (!pack.getRetransmitted()) return;
		if (!routerEvent.isDiscarded()) return;
		
		listMap.get(pack.getSessionId()).put(pack.getSentTime(), pack.getSessionId().doubleValue());
	}

	@Override
	protected void finishStatistic() {
		final ScatterPlotChart chart = new ScatterPlotChart(getTitle(), getxLabel(), getyLabel(), this.listMap);
		try {
			chart.saveAsImage(getTitle().replaceAll(" ", ""));
		} catch (IOException e) {
			logger.error("Falha ao salvar grafico.", e);
		}
	}

}
